// register业务模块
console.log( 'register业务模块' )

import axios from 'axios'

let email = document.querySelector('#email')
let btnSuccess = document.querySelector('.btn-success')
btnSuccess.onclick = function (){
    // 获取输入的邮箱
    let email_val = email.value
    // 验证邮箱的正则
    // '2239222721@qq.com'
    // 'xiaocuo_123@sohu.com'
    // 'taoshujian@yahoo.com.cn'
    let reg = /^\w{6,22}@[0-9a-zA-Z]{1,13}(\.[a-zA-Z]{2,3}){1,2}$/
    if (!reg.test(email_val)) {
        alert('邮箱格式错误！')
        return
    }
    
    // 发送注册验证码
    axios({
        method: 'post',
        url: 'http://localhost:8080/users/sendMail',
        data: {email:email_val}
    })
    .then((res)=>{
        alert(res.data.msg)
    })
}

// 注册账号
let btnPrimary = document.querySelector('.btn-primary')
btnPrimary.onclick = function (){
    // 获取输入的注册信息
    let user = document.querySelector('#user').value
    let pass = document.querySelector('#pass').value
    let age = document.querySelector('#age').value
    let sex = document.querySelector('#sex').value
    let email = document.querySelector('#email').value
    let code = document.querySelector('#search-ipt').value
    let nick = document.querySelector('#nick').value

    // 验证注册信息
    let regUser = /^\w{6,18}$/
    if (!regUser.test(user)) {
        alert('账号格式错误')
        return
    }

    let regPass = /^\w{6,18}$/
    if (!regPass.test(pass)) {
        alert('密码格式错误')
        return
    }

    let regAge = /^\d{1,3}$/
    if (!regAge.test(age)) {
        alert('年龄格式错误')
        return
    }

    if (!sex) {
        alert('请选择性别')
        return
    }

    let regEmail = /^\w{6,22}@[0-9a-zA-Z]{1,13}(\.[a-zA-Z]{2,3}){1,2}$/
    if (!regEmail.test(email)) {
        alert('邮箱格式错误！')
        return
    }

    let regCode = /^\d{2,8}$/
    if (!regCode.test(code)) {
        alert('验证码格式错误')
        return
    }

    let regNick = /^.{2,12}$/
    if (!regNick.test(nick)) {
        alert('验证码格式错误')
        return
    }

    // 发送注册请求
    axios({
        method: 'post',
        url: 'http://localhost:8080/users/register',
        data: {user,pass,age,sex,nick,code,email},
    })
    .then((res)=>{
        alert(res.data.msg)
        if (res.data.code === 1) {
            // 注册成功跳转到首页
            location.href = './index.html'
        }
    })
}
